﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Meechisoft.TFS.BranchIndicator
{
    using EnvDTE;
    using Microsoft.TeamFoundation.Client;
    using Microsoft.TeamFoundation.VersionControl.Client;

    public static class TfsHelpers
    {
        public static BranchObject GetBranchFromSolution(IServiceProvider provider, Solution solution, ITeamFoundationContext context)
        {
            if (context == null)
                return null;

            var vcs = context.TeamProjectCollection.GetService(typeof(VersionControlServer)) as VersionControlServer;

            if (String.IsNullOrWhiteSpace(solution.FullName) || vcs == null)
                return null;

            var ws = vcs.TryGetWorkspace(solution.FullName);
            if (ws == null)
                return null;

            var serverPath = ws.TryGetServerItemForLocalItem(solution.FullName);
            if (String.IsNullOrWhiteSpace(serverPath))
                return null;

            return GetBranch(serverPath, vcs);
        }

        public static BranchObject GetBranch(string serverPath, VersionControlServer vcs)
        {
            serverPath = serverPath ?? String.Empty;

            foreach (var branch in GetBranches(vcs))
            {
                var branchPath = branch.Properties.RootItem.Item;
                if (serverPath.StartsWith((branchPath.EndsWith("/") ? branchPath : branchPath + "/"), StringComparison.OrdinalIgnoreCase))
                    return branch;
            }

            return null;
        }

        public static IEnumerable<BranchObject> GetBranches(VersionControlServer vcs)
        {
            var branches = vcs.QueryRootBranchObjects(RecursionType.OneLevel);

            foreach (var b1 in branches)
            {
                foreach (var b2 in RecurseBranches(b1, vcs))
                    yield return b2;
            }
        }

        private static IEnumerable<BranchObject> RecurseBranches(BranchObject branch, VersionControlServer vcs)
        {
            yield return branch;

            var childBos = vcs.QueryBranchObjects(branch.Properties.RootItem, RecursionType.OneLevel);

            foreach (var child in childBos)
            {
                if (child.Properties.RootItem.Item == branch.Properties.RootItem.Item)
                    continue;

                foreach (var b2 in RecurseBranches(child, vcs))
                    yield return b2;
            }
        }


      
    }
}
